const fs = require('graceful-fs')
const glob = require('glob')
const path = require('path')

// import os from 'os';

const writeToFileIfChanged = (filename, content) => {
  if (fs.existsSync(filename)) {
    const currentInput = fs.readFileSync(filename, 'utf-8')

    if (currentInput !== content) {
      writeFile(filename, content)
    }
  } else {
    writeFile(filename, content)
  }
}

const writeFile = (filename, content) => {
  // Replace new lines with OS-specific new lines
  // content = content.replace(/\n/g, os.EOL);

  fs.writeFileSync(filename, content, 'utf8')
}

const filenameToInterfaceName = filename => {
  return path
    .basename(filename)
    .replace(/^(\w)/, (_, c) => `I${c.toUpperCase()}`)
    .replace(/\W+(\w)/g, (_, c) => c.toUpperCase())
}

const generate = (filename, classes) => {
  const interfaceName = filenameToInterfaceName(filename)
  const interfaceProperties = classes
    .map(key => {
      const indent = '  '
      const newKey = key.replace('.', '').replace('{', '')

      return `${indent}${newKey}: string`
    })
    .join('\n')

  return `export interface ${interfaceName} {
${interfaceProperties}
}
declare const styles: ${interfaceName}

export default styles
`
}

glob('src/**/*.+(le|c)ss', {}, (err, res) => {
  if (!res) return
  res.forEach(f => {
    const content = fs.readFileSync(f, 'utf8').replace(/(\s*)\{/g, '{')

    // console.log(content)
    const classAry = content.match(/\.(\w*)\{/g)

    // console.log(classAry)
    const result = generate(f, [...new Set(classAry)])
    writeToFileIfChanged(`${f}.d.ts`, result)
  })
})
